package net.ibizsys.eclipse.studio.file;

import java.io.File;

import net.ibizsys.eclipse.studio.Activator;
import net.ibizsys.eclipse.studio.util.FileKit;
import net.ibizsys.eclipse.studio.xml.IBizFile;

/**
 * 服务类文件构建器<主要指各类java文件>
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public abstract class SFFileBuilder extends BaseFileBuilder
{
	private StringBuilder builder = new StringBuilder();

	@Override
	public boolean init()
	{
		return initContentBuilder(builder);
	}

	protected boolean initContentBuilder(StringBuilder builder)
	{
		builder.append("package %1$s;\n");
		builder.append("\n");

		onInitDependPackage(builder);
		onInitDoc(builder);
		onInitAnnotation(builder);

		builder.append("public class %3$s extends %4$s {\n");
		builder.append("\n");

		onInitProperties(builder);

		if (hasException())
		{
			builder.append("    public %3$s() throws Exception {\n");
		} else
		{
			builder.append("    public %3$s() {\n");
		}

		builder.append("        super();\n");
		builder.append("    }\n");
		builder.append("\n");
		builder.append("}\n");

		return true;
	}

	/**
	 * 初始化依赖包
	 * 
	 * @param builder
	 */
	protected void onInitDependPackage(StringBuilder builder)
	{
		builder.append("import net.ibizsys.paas.util.spring.IBizOverride;\n");
		builder.append("\n");
	}

	/**
	 * 初始化类注释
	 * 
	 * @param builder
	 */
	protected void onInitDoc(StringBuilder builder)
	{
		builder.append("/**\n");
		builder.append(" * \n");
		builder.append(" * \n");
		builder.append(" * @author %2$s\n");
		builder.append(" */\n");
	}

	/**
	 * 初始化注解
	 * 
	 * @param builder
	 */
	protected void onInitAnnotation(StringBuilder builder)
	{
		builder.append("@IBizOverride\n");
	}

	/**
	 * 构造函数是否有异常
	 * 
	 * @return
	 */
	protected boolean hasException()
	{
		return false;
	}

	/**
	 * 初始化属性
	 * 
	 * @param builder
	 */
	protected void onInitProperties(StringBuilder builder)
	{

	}

	@Override
	public boolean build(IBizFile baseFile)
	{
		File file = new File(baseFile.getUsrRealFilePath());

		String strSuper = FileKit.prefix(baseFile.getName());
		String strClazz = FileKit.prefix(file.getName());

		String strContent = String.format(builder.toString(), packageName(baseFile), Activator.getDefault().curUser().getName(), strClazz, strSuper);

		return FileKit.mkfile(file, strContent);
	}

	private String packageName(IBizFile baseFile)
	{
		String val = baseFile.getPath().replaceAll("[/]", ".");

		return val.replaceAll("[\\\\]", ".");
	}
}
